const http = require("http");
const fs = require("fs");
const path = require("path");

http.createServer((req,res) => {
    var urlObj = new URL(req.url, "http://localhost:8081");
    var pathName = urlObj.pathname;

    if(pathName == "/"){
        var fileContent = fs.readFileSync("./index.html");
        res.writeHead(200, {"Context-Type": "text/html;charset=utf8"});
        res.write(fileContent);
        res.end();
    }
    else{
        var str = "";
        req.setEncoding("binary");
        req.on("data", (chunk) => {
            str += chunk;
        })
        req.on("end", () => {
            var arr = str.split("\r\n");
            var imgArr = arr.slice(4, arr.length-2);
            var imgStr = imgArr.join("\r\n");
            var buf = Buffer.from(imgStr, "binary");
            fs.writeFileSync(path.join(__dirname, "/upload/2.png"), buf, {"encoding": "binary"});
        })
    }
}).listen(8081);

